package springboot.study.project.service.impl;

import org.apache.ibatis.session.RowBounds;
import org.apache.poi.ss.formula.functions.Count;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springboot.study.project.constant.SessionConstant;
import springboot.study.project.dto.BulletinDto;
import springboot.study.project.mapper.BulletinMapper;
import springboot.study.project.mapper.UserMapper;
import springboot.study.project.model.Bulletin;
import springboot.study.project.model.BulletinExample;
import springboot.study.project.model.User;
import springboot.study.project.model.UserExample;
import springboot.study.project.service.BulletinService;
import springboot.study.project.util.common.SessionUtil;
import springboot.study.project.util.common.StringUtil;
import springboot.study.project.util.common.Util;
import springboot.study.project.util.date.DateUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: BulletinServiceImpl
 * @Description: 公告接口实现类
 * @Author: liu-hao
 * @Date: 2021-03-31 23:11
 * @Version: 1.0
 **/
@Service
public class BulletinServiceImpl implements BulletinService {

    @Autowired
    BulletinMapper bulletinMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public boolean pushBulletin(Bulletin bulletin, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return false;
        }
        boolean result = false;
        if (bulletin.getBulletinId() == null) { // 添加
            bulletin.setReadCount(0);
            bulletin.setPublisher(user.getId());
            bulletin.setGmtCreate(System.currentTimeMillis());
            bulletin.setGmtModify(bulletin.getGmtCreate());
            int insertCount = bulletinMapper.insert(bulletin);
            result = insertCount > 0 ? true : false;
        } else { // 更新
            bulletin.setGmtModify(System.currentTimeMillis());
            int updateCount = bulletinMapper.updateByPrimaryKey(bulletin);
            result = updateCount > 0 ? true : false;
        }
        return result;
    }

    @Override
    public boolean removeBulletin(String bulletinId) {
        if (StringUtil.isNotBlank(bulletinId)) {
            int deleteCount = bulletinMapper.deleteByPrimaryKey(Util.getIntOfObj(bulletinId));
            return deleteCount > 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean modifyBulletin(Bulletin bulletin) {
        if (bulletin != null && StringUtil.isNotBlank(bulletin.getBulletinId())) {
            bulletin.setGmtModify(System.currentTimeMillis());
            int updateCount = bulletinMapper.updateByPrimaryKeySelective(bulletin);
            return updateCount > 0 ? true : false;
        }
        return false;
    }

    @Override
    public Bulletin getBulletinById(String bulletinId) {
        if (StringUtil.isNotBlank(bulletinId)) {
            Bulletin bulletin = bulletinMapper.selectByPrimaryKey(Util.getIntOfObj(bulletinId));
            return bulletin;
        }
        return null;
    }

    @Override
    public List<Bulletin> getHotBulletins() {
        int offset = 0;
        int pageSize = 5;
        BulletinExample example = new BulletinExample();
        example.setOrderByClause("gmt_modify desc");
        List<Bulletin> bulletins = bulletinMapper.selectByExampleWithRowbounds(example, new RowBounds(offset, pageSize));
        return bulletins;
    }

    @Override
    public Map<String, Object> getBulletins(String bulletinTitle, String publisherName, String dateRange, int offset, int pageSize) {
        BulletinExample example = new BulletinExample();
        BulletinExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(bulletinTitle)) {
            criteria.andBulletinTitleLike("%" + bulletinTitle + "%");
        }
        if (StringUtil.isNotBlank(publisherName)) {
            UserExample userExample = new UserExample();
            userExample.createCriteria().andRealNameLike("%" + publisherName + "%");
            List<User> users = userMapper.selectByExample(userExample);
            List<Integer> userIds = users.stream().map(user -> user.getId()).collect(Collectors.toList());
            if (userIds.size() <= 0)
                userIds.add(-999);
            criteria.andPublisherIn(userIds);

        }
        if (StringUtil.isNotBlank(dateRange) && dateRange.split(" - ").length == 2) {
            String startDate = dateRange.split(" - ")[0].trim();
            String endDate = dateRange.split(" - ")[1].trim();
            Long startTimestamp = DateUtil.dateStrToTimestamp(DateUtil.PATTERN_NYR, startDate);
            Long endTimestamp = DateUtil.dateStrToTimestamp(DateUtil.PATTERN_NYR, endDate);
            criteria.andGmtModifyBetween(startTimestamp, endTimestamp);
        }
        // 查询符合条件公告数量
        int totalCount = bulletinMapper.countByExample(example);
        // 查询符合条件的公告信息
        List<Bulletin> bulletins = bulletinMapper.selectByExampleWithRowbounds(example, new RowBounds(offset, pageSize));

        // 填充公告属性
        List<BulletinDto> bulletinDtos = new ArrayList<>();
        for (Bulletin bulletin : bulletins) {
            BulletinDto bulletinDto = new BulletinDto();

            User user = null;
            if (StringUtil.isNotBlank(bulletin.getPublisher())) {
                user = userMapper.selectByPrimaryKey(bulletin.getPublisher());
                if (user != null)
                    BeanUtils.copyProperties(user, bulletinDto);
            }
            // 将两个对象中相同字段的属性值自动拷贝到另一个实体对象中去
            BeanUtils.copyProperties(bulletin, bulletinDto);
            bulletinDto.setGmtCreateStr(DateUtil.getDateStr(DateUtil.PATTERN_NYRSFM, new Date(bulletinDto.getGmtCreate())));
            bulletinDto.setGmtModifyStr(DateUtil.getDateStr(DateUtil.PATTERN_NYRSFM, new Date(bulletinDto.getGmtModify())));
            bulletinDtos.add(bulletinDto);
        }


        // 定义返回Map
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("msg", 0);
        resultMap.put("count", totalCount);
        resultMap.put("data", bulletinDtos);
        return resultMap;
    }
}
